package com.saianfu.flowable.demo.common.impl

import com.saianfu.flowable.demo.common.ActProcess
import org.flowable.engine.RepositoryService
import org.flowable.engine.repository.*
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.io.InputStream

/**
 * 流程定义
 *
 */
@Component
class ProcessHandler : ActProcess {

    @Autowired
    lateinit var repositoryService: RepositoryService

    override fun createDeployment(): DeploymentBuilder {
        return repositoryService.createDeployment()
    }

    override fun createDeploymentQuery(): DeploymentQuery {
        return repositoryService.createDeploymentQuery()
    }

    override fun createProcessDefinitionQuery(): ProcessDefinitionQuery {
        return repositoryService.createProcessDefinitionQuery()
    }

    override fun deploy(bpmnFileUrl: String): Deployment {
        return createDeployment().addClasspathResource(bpmnFileUrl).deploy()
    }

    override fun deploy(url: String, pngUrl: String?): Deployment {
        return createDeployment().addClasspathResource(url).addClasspathResource(pngUrl).deploy()
    }

    override fun deployBpmnAndDrl(url: String, drlUrl: String): Deployment {
        return createDeployment().addClasspathResource(url).addClasspathResource(drlUrl).deploy()
    }

    override fun deploy(url: String, name: String?, category: String?): Deployment {
        return createDeployment().addClasspathResource(url).name(name).category(category).deploy()
    }

    override fun deploy(url: String, pngUrl: String?, name: String?, category: String?): Deployment {
        return createDeployment().addClasspathResource(url).addClasspathResource(pngUrl)
                .name(name).category(category).deploy()
    }

    override fun exist(processDefinitionKey: String): Boolean {
        val processDefinitionQuery = createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey)
        val count = processDefinitionQuery.count()
        return if (count > 0) true else false
    }

    override fun deploy(name: String, category: String, `in`: InputStream): Deployment {
        return createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, `in`).name(name).category(category).deploy()
    }

    override fun queryByProcessDefinitionKey(processDefinitionKey: String): ProcessDefinition {
        return createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).active().singleResult()
    }

    companion object {
        protected var logger = LoggerFactory.getLogger(ProcessHandler::class.java)

        /**
         * 解决问题：https://blog.csdn.net/weixin_43607664/article/details/88664777
         */
        const val BPMN_FILE_SUFFIX = ".bpmn"
    }
}